<?php
/**
 * 微信分享
*/
class b2c_share_JSSDK{
  private $token;
  private $appId;
  private $appSecret;

  public function __construct($token, $appId, $appSecret) {
    $res = kernel::single('weixin_mdl_bind')->dump(array('status'=>'active'),'token,appid,appsecret');
    $this->token = $res['token'];
    $this->appId = $res['appid'];
    $this->appSecret = $res['appsecret'];
  }

  public function getSignPackage($url='') {
    $jsapiTicket = $this->getJsApiTicket();
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $url = !empty($url) ? urldecode($url) : "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    $timestamp = time();					//生成签名的时间戳
    $nonceStr = $this->createNonceStr();	//生成签名的随机串

    // 这里参数的顺序要按照 key 值 ASCII 码升序排序
    $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

    $signature = sha1($string);

    $signPackage = array(
        "appId"     => $this->appId,
        "nonceStr"  => $nonceStr,
        "timestamp" => $timestamp,
        "url"       => $url,
        "signature" => $signature,
        "rawString" => $string
    );
    return $signPackage;
  }

  private function createNonceStr($length = 16) {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $str = "";
    for ($i = 0; $i < $length; $i++) {
      $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
  }

  // jsapi_ticket 全局存储与更新
  private function getJsApiTicket() {
    $jsapi_ticket_file = "./data/cache/jsapi_ticket";
    if(!is_file($jsapi_ticket_file)){
      $this->mkdirs($jsapi_ticket_file);
    }
    $jsapi_ticket_name = $jsapi_ticket_file."/".$this->token.".json";
    $data = json_decode(file_get_contents($jsapi_ticket_name));
    if ($data->expire_time < time() || $data->appid != $this->appId) {
      $accessToken = $this->getAccessToken();
      $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
      $res = json_decode($this->httpGet($url));
      $ticket = $res->ticket;
      if ($ticket) {
        $data->token = $this->token;
        $data->appid = $this->appId;
        $data->appsecret = $this->appSecret;
        $data->expire_time = time() + 7000;
        $data->jsapi_ticket = $ticket;
        $fp = fopen($jsapi_ticket_name, "w");
        fwrite($fp, json_encode($data));
        fclose($fp);
      }
    } else {
      $ticket = $data->jsapi_ticket;
    }
    return $ticket;
  }

  // access_token 全局存储与更新
  public function getAccessToken() {
    $access_token_file = "./data/cache/access_token";
    if(!is_file($access_token_file)){
      $this->mkdirs($access_token_file);
    }
    $access_token_name = $access_token_file."/".$this->token.".json";
    $data = json_decode(file_get_contents($access_token_name));

    if ($data->expire_time < time() || $data->appid != $this->appId) {
      $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
      $res = json_decode($this->httpGet($url));
      $access_token = $res->access_token;
      if ($access_token) {
        $data->token = $this->token;
        $data->appid = $this->appId;
        $data->appsecret = $this->appSecret;
        $data->expire_time = time() + 7000;
        $data->access_token = $access_token;
        $fp = fopen($access_token_name, "w");
        fwrite($fp, json_encode($data));
        fclose($fp);
      }
    } else {
      $access_token = $data->access_token;
    }
    return $access_token;
  }


  private function httpGet($url) {
    $ch = curl_init();
    $header = "Accept-Charset: utf-8";
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $temp = curl_exec($ch);
    curl_close($ch);
    return $temp;
  }
  /**
   * 按指定路径生成目录
   * @param string $path   路径
   */
  function mkdirs($path){
    $adir = explode('/',$path);
    $dirlist = '';
    $rootdir = array_shift($adir);
    if(($rootdir!='.'||$rootdir!='..')&&!is_file($rootdir)){
      @mkdir($rootdir);
    }
    foreach($adir as $key=>$val){
      if($val!='.'&&$val!='..'){
        $dirlist .= "/".$val;
        $dirpath = $rootdir.$dirlist;
        if(!is_file($dirpath)){
          @mkdir($dirpath);
          @chmod($dirpath,0777);
        }
      }
    }
  }
}